<template>
    <el-card style="width: 100%;margin: 0;" shadow="always">
        <template #header>
            <div class="card-header">
                <el-form :inline="true" :model="findForm" class="demo-form-inline">
                    <el-form-item label="项目名称：">
                        <el-input v-model="findForm.name" placeholder="请输入项目名称" style="width: 200px" clearable />
                    </el-form-item>
                    <el-form-item label="项目类别">
                        <el-select v-model="findForm.type" placeholder="请选择..." style="width: 200px" clearable>
                            <el-option v-for="item in itemTypeArr" :key="item.id" :label="item.name" :value="item.name">
                                <span style="float: left">{{ item.name }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="项目状态">
                        <el-select v-model="findForm.status" placeholder="请选择" style="width: 200px" clearable>
                            <el-option v-for="item in itemStatusArr" :label="item.label" :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="itemFindAll(findForm)">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" @click="addItem()">添加项目</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <div class="box">
            <div v-for="item in itemArr" :key="item.id">
                <el-card style="width: 400px">
                    <template #header>
                        <div class="card-header">
                            <div>
                                <el-tag :key="item.statusStr" :type="getItemType(itemStatusArr, item.status)"
                                    effect="dark">
                                    {{ item.status }}
                                </el-tag>
                            </div>
                            <div>
                                <el-button type="primary" :icon="Edit" circle @click="updateItem(item)" />
                                <el-button type="danger" :icon="Delete" circle @click="deleteItem(item.id)" />
                            </div>
                        </div>
                    </template>
                    <table>
                        <tr>
                            <td><span>项目图片：</span></td>
                            <td><el-image v-if="item.image" style="width: 100px; height: 100px" :src="item.image"
                                    :preview-src-list="[item.image]" fit="fill" /></td>
                        </tr>
                        <tr>
                            <td><span>项目名称：</span></td>
                            <td>{{ item.name }}</td>
                        </tr>
                        <tr>
                            <td><span>项目类型：</span></td>
                            <td>{{ item.type }}</td>
                        </tr>
                        <tr>
                            <td><span>项目负责人：</span></td>
                            <td>{{ item.student }}</td>
                        </tr>
                        <tr>
                            <td><span>项目团队：</span></td>
                            <td>{{ item.team }}</td>
                        </tr>
                        <tr>
                            <td><span>指导教师：</span></td>
                            <td>{{ item.teacher }}</td>
                        </tr>
                        <tr>
                            <td><span>所属学院：</span></td>
                            <td>{{ item.college }}</td>
                        </tr>
                        <tr>
                            <td><span>项目文档：</span></td>
                            <td><el-tooltip class="box-item" effect="dark" :content="item.files"
                                    placement="bottom"><span>{{
                                        item.files }}</span></el-tooltip></td>
                        </tr>
                        <tr>
                            <td><span>项目创建时间：</span></td>
                            <td>{{ dataFormat(item.createdAt) }}</td>
                        </tr>
                        <tr>
                            <td><span>项目修改时间：</span></td>
                            <td>{{ dataFormat(item.updatedAt) }}</td>
                        </tr>
                    </table>
                    <template #footer>
                        <el-button type="primary" @click="onSubmitAudit(item)">提交审核</el-button>

                    </template>
                </el-card>
            </div>
        </div>
        <template #footer>
            <el-pagination v-model:current-page="findForm.currentPage" v-model:page-size="findForm.pageSize"
                :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </template>
    </el-card>
    <!-- 添加和修改操作 -->
    <el-drawer v-model="drawerForm" :title="drawerTitle" direction="rtl" size="30%">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="itemForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="项目图片" prop="image">
                <el-upload class="avatar-uploader" active="#" :limit="1" :show-file-list="false"
                    :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                    <el-image v-if="itemForm.image" style="width: 100px; height: 100px" :src="itemForm.image"
                        :preview-src-list="itemForm.image" fit="fill" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="项目名称" prop="name">
                <el-input v-model="itemForm.name" />
            </el-form-item>
            <el-form-item label="项目类别" prop="type">
                <el-select v-model="itemForm.type" placeholder="请选择...">
                    <el-option v-for="item in itemTypeArr" :key="item.id" :label="item.name" :value="item.id">
                        <span style="float: left">{{ item.name }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="项目负责人" prop="student">
                <el-input v-model="itemForm.student" />
            </el-form-item>
            <el-form-item label="项目团队" prop="team">
                <el-input v-model="itemForm.team">
                    <template #suffix>
                        <el-icon class="el-input__icon" @click="chooseDate({ type: 'team', number: 9 })">
                            <HomeFilled />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="指导教师" prop="teacher">
                <el-input v-model="itemForm.teacher">
                    <template #suffix>
                        <el-icon class="el-input__icon" @click="chooseDate({ type: 'user', number: 5 })">
                            <Avatar />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="工作单位：" prop="college">
                <el-select v-model="itemForm.college" filterable remote :remote-method="universityFindAll()"
                    placeholder="请输入工作单位">
                    <el-option v-for="item in universityArr" :key="item.id" :label="item.universityName"
                        :value="item.id">
                        <span style="float: left">{{ item.universityName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="项目文档" prop="files">
                <el-upload class="upload-demo" :file-list="fileList" action="#" :limit="1" :on-change="handleChange"
                    :on-preview="handlePreview" :before-upload="beforeAvatarUpload1" :http-request="handleFileUpload1">
                    <el-button type="primary">上传文档</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            doc/docx 文件不能超过 8M，且只能上传 doc/docx 文件。
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addOrUpdateItem({ title: drawerTitle, data: itemForm })">
                    提交
                </el-button>
                <el-button @click="drawerForm = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
    <!-- 选择成员和项目 -->
    <el-dialog v-model="dialogForm1" :title="dialogTitle1" width="660">
        <el-table :data="dateArr" style="width: 100%" max-height="500" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column type="index" width="50" />
            <el-table-column v-if="dateNumber != 9" property="avatarUrl" label="头像" width="110">
                <template #default="scope">
                    <div>
                        <el-image v-if="scope.row.avatarUrl" style="width: 100px; height: 100px"
                            :src="scope.row.avatarUrl" :preview-src-list="[scope.row.avatarUrl]" fit="fill" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="dateNumber != 9" property="userName" label="用户名" width="80" />
            <el-table-column v-if="dateNumber == 9" property="name" label="用户名" width="80" />
            <el-table-column v-if="dateNumber == 9" property="userNameOne" label="成员1" width="80" />
            <el-table-column v-if="dateNumber == 9" property="userNameTwo" label="成员2" width="80" />
            <el-table-column v-if="dateNumber == 9" property="userNameThree" label="成员3" width="80" />
            <el-table-column label="确认" width="200">
                <template #default="scope">
                    <el-button v-if="dateNumber != 9" type="primary"
                        @click="passOnDate(scope.row.userName)">选择</el-button>
                    <el-button v-if="dateNumber == 9" type="primary" @click="passOnDate(scope.row.name)">选择</el-button>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogForm1 = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus';
import { Delete, Edit, Plus, HomeFilled, Avatar } from '@element-plus/icons-vue';
// 后端接口
import { FindAllItem, AddItem, UpdateItem, DeleteItem } from '../../api/item';
import { FindAllUserItem } from '../../api/userItem';
import { findAllUser } from '../../api/user';
import { Upload } from '../../api/upload';
import { FindAllItemType } from '../../api/itemType';
import { getByNameUn } from '../../api/university';
import { AddAudit } from '../../api/audit';

import dayjs from "dayjs";

// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId') + ''
if (errorId == undefined || errorId == '' || (errorId != '1' && errorId != '2')) {
    sessionStorage.setItem('error', 'not')
    router.push("/LimitsAuthority")
}

// 项目状态参数
const itemStatusArr = [
    {
        value: 0,
        label: '草稿',
        type: 'info',
    },
    {
        value: 1,
        label: '已提交',
        type: 'success',
    },
    {
        value: 2,
        label: '审核中',
        type: 'primary',
    },
    {
        value: 3,
        label: '已通过',
        type: 'success',
    },
    {
        value: 4,
        label: '已驳回',
        type: 'danger',
    },
    {
        value: 5,
        label: '已完成',
        type: 'success',
    },
]
// 学校信息
const universityArr = ref([] as any[]);
const universityFindAll = () => {
    getByNameUn({ name: itemForm.college }).then((res: any) => {
        if (res.code == 2000) {
            universityArr.value = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
// 查询信息参数
const findForm = reactive({
    student: (Number)(sessionStorage.getItem('userId')),
    name: '',
    type: '',
    status: '',
    currentPage: 1,
    pageSize: 5,
})
// 项目信息
const itemArr = ref([] as any[]);
// 加载项目信息
const itemFindAll = (findForm: any) => {
    FindAllItem(findForm).then((res: any) => {
        console.log(res)
        if (res.code == 2000) {
            itemArr.value = res.data.data
            total.value = res.data.total
        } else {
            ElMessage.error(res.message)
        }
    })
}
itemFindAll(findForm)
// 项目类别
const itemTypeArr = ref([] as any[]);
const itemTypeFindAll = () => {
    FindAllItemType({}).then((res: any) => {
        console.log(res)
        if (res.code == 2000) {
            itemTypeArr.value = res.data
        } else {
            ElMessage.error(res.message)
        }
    })

}
itemTypeFindAll()
// 抽屉参数
const drawerForm = ref(false)
const drawerTitle = ref('')
const dialogForm1 = ref(false)
const dialogTitle1 = ref('')
const openDrawer = (drawerData: string) => {
    drawerForm.value = true
    drawerTitle.value = drawerData
}
const openDialog1 = (dialogData: string) => {
    dialogForm1.value = true
    dialogTitle1.value = dialogData
}
const dateArr = ref([] as any[])
const dateNumber = ref(0)
const passOnDate = (date: string) => {
    if (dateNumber.value == 1) {
        itemForm.student = date
    } else if (dateNumber.value == 5) {
        itemForm.teacher = date
    } else if (dateNumber.value == 9) {
        itemForm.team = date
    }
    dialogForm1.value = false
}
// 选择信息
const chooseDate = (date: any) => {
    dateNumber.value = date.number
    if (date.type == 'team') {
        openDialog1('选择团队')
        FindAllUserItem({ userId: (Number)(sessionStorage.getItem('userId') + '') }).then((res: any) => {
            if (res.code == 2000) {
                dateArr.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    } else if (date.type == 'user') {
        openDialog1('选择成员')
        if (date.number == 1) {
            findAllUser({ roleId: 1 }).then((res: any) => {
                if (res.code == 2000) {
                    dateArr.value = res.data
                } else {
                    ElMessage.error(res.message)
                }
            })
        } else if (date.number == 5) {
            findAllUser({ roleId: 2 }).then((res: any) => {
                if (res.code == 2000) {
                    dateArr.value = res.data
                } else {
                    ElMessage.error(res.message)
                }
            })
        }

    }

}
const auditForm = reactive({
    id: 0,
    itemId: 0,
    userId: '',
    status: 0,
    text: '',
    itemName: '',
})
// 提交审核
const onSubmitAudit = (data: any) => {
    data.status = 2
    auditForm.status = 2
    auditForm.itemId = data.id
    UpdateItem(data).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '提交审核成功',
                type: 'success',
            });
            itemFindAll(findForm);
            AddAudit(auditForm).then((res: any) => {
                if (res.code == 2000) {
                    ElNotification({
                        title: '成功',
                        message: '添加审核成功',
                        type: 'success',
                    });
                } else {
                    ElMessage.error(res.message);
                }
            });
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 添加和修改操作
const addItem = () => {
    openDrawer('添加项目信息')
    itemForm.id = 0
    itemForm.image = ""
    itemForm.name = ""
    itemForm.type = ""
    itemForm.student = sessionStorage.getItem('userName') + ''
    itemForm.team = ""
    itemForm.teacher = ""
    itemForm.college = ""
    fileList.value = []
}
const updateItem = (data: any) => {
    openDrawer('修改项目信息')
    itemForm.id = data.id
    itemForm.image = data.image
    itemForm.name = data.name
    itemForm.type = data.type
    itemForm.student = data.student
    itemForm.team = data.team
    itemForm.teacher = data.teacher
    itemForm.college = data.college
    fileList.value = [{ name: data.name, url: data.files }]
    itemForm.files = data.files
    itemForm.status = getItemValue(itemStatusArr, data.status)
    itemForm.isDel = data.isDel
}
const addOrUpdateItem = (data: any) => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加项目信息') {
                AddItem(itemForm).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        itemFindAll(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改项目信息') {
                UpdateItem(data.data).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        itemFindAll(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
// 删除操作
const deleteItem = (data: any) => {
    DeleteItem({id: (Number)(data)}).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            itemFindAll(findForm);
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 文件上传参数
const fileList = ref<UploadUserFile[]>([
    //   {
    //     name: 'food.jpeg',
    //     url: itemForm.files,
    //   },
])
const handlePreview: UploadProps['onPreview'] = (file) => {
    // 创建一个隐藏的<a>元素
    const link = document.createElement('a');
    link.href = itemForm.files;
    link.download = file.name;
    // 将<a>元素添加到DOM中
    document.body.appendChild(link);
    // 触发点击事件以开始下载
    link.click();
    // 下载完成后移除<a>元素
    document.body.removeChild(link);
}
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile.name)
    console.log(uploadFiles)
    uploadFile.url = itemForm.files
    // fileList.value = fileList.value.slice(-1)
}
const handleFileUpload1 = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', sessionStorage.getItem("userId") + '')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            itemForm.files = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile.type)
    const validTypes = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 doc 或 docx 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 8) {
        ElMessage.error('文件大小不能超过 8MB!');
        return false;
    }
    return true
}
const handleFileUpload = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', sessionStorage.getItem("userId") + '')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            itemForm.image = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const validTypes = ['image/jpeg', 'image/png'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 jpg 或 png 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过 2MB!');
        return false;
    }
    return true
}

// 表单验证
interface RuleForm {
    id: number
    image: string
    name: string
    type: string
    student: string
    team: string
    teacher: string
    college: string
    files: string
    status: string
    isDel: string
}

const ruleFormRef = ref<FormInstance>()
const itemForm = reactive<RuleForm>({
    id: 0,
    image: '',
    name: '',
    type: '',
    student: '',
    team: '',
    teacher: '',
    college: '',
    files: '',
    status: '',
    isDel: '',
})

const rules = reactive<FormRules<RuleForm>>({
    image: [
        { required: true, message: '请添加项目图片', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '请添加项目名称', trigger: 'blur' },
        { max: 10, message: '不能超过10个字', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请选择项目类别', trigger: 'blur' },
    ],
    student: [
        { required: true, message: '请添加项目负责人', trigger: 'blur' },
    ],
    team: [
        { required: true, message: '请添加项目成员', trigger: 'blur' },
    ],
    teacher: [
        { required: true, message: '请添加指导教师', trigger: 'blur' },
    ],
    college: [
        { required: true, message: '请添加所属学校', trigger: 'blur' },
    ],
    files: [
        { required: true, message: '请添加项目文档', trigger: 'blur' },
    ],
})
// 分页参数
const total = ref(5)
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    findForm.pageSize = val
    itemFindAll(findForm)
}
const handleCurrentChange = (vals: number) => {
    console.log(`current page: ${vals}`)
    findForm.currentPage = vals
    itemFindAll(findForm)
}

// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
// 遍历数组
const getItemType = (itemTypeArr: any, value: any) => {
    for (let i = 0; i < itemTypeArr.length; i++) {
        if (itemTypeArr[i].label == value) {
            return itemTypeArr[i].type
        }
    }
}
const getItemValue = (itemTypeArr: any, value: any) => {
    for (let i = 0; i < itemTypeArr.length; i++) {
        if (itemTypeArr[i].label == value) {
            return itemTypeArr[i].value
        }
    }
}
</script>

<style scoped>
.box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: start;
}

.el-card {
    width: 300px;
    margin: 5px 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
}

table {
    width: 100%;
    font-size: 16px;
}

table tr {
    width: 100%;
}

table td span {
    width: 120px;
    display: block;
    text-align: right;
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 在文本溢出时显示省略号。 */
}

.el-upload__tip {
    height: 25px;
    margin: 0;
}

/* 上传图片 */
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>